package com.jian.socks5.tcp.handler;

import com.jian.socks5.common.Constants;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/****
 * 目标转发到客户端
 * @author Jian
 * @date 2021.06.20
 */
@ChannelHandler.Sharable
public class Server2ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        ChannelHandlerContext channelHandlerContext = channel.attr(Constants.DEST_CHANNEL_ATTR).get();
        String ipAndPort = channel.attr(Constants.CHANNEL_ATTR_IPINFO).get();
        if (channelHandlerContext != null) {
            //关闭连接的目标机器
            channelHandlerContext.close();
        }
        //关闭异常连接
        ctx.close();
        System.err.println("Server2ClientHandler异常，已关闭目标连接和客户端连接！IP:" + ipAndPort + "__" + cause.getMessage());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ChannelHandlerContext channelHandlerContext = ctx.channel().attr(Constants.DEST_CHANNEL_ATTR).get();
        if (channelHandlerContext != null) {
            channelHandlerContext.writeAndFlush(msg);
        }
    }
}
